﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Providers.Objetos
{
    public class Provider : ProviderBase, IProvider
    {
        CoreEntities entities { get { return new CoreEntities(); } }

        public Provider()
        { }

        public Objeto Insert(Objeto item)
        {
            using (var db = this.entities)
            {
                db.Objetos.Add(item);
                db.SaveChanges();
                return Get(item.Guid);
            }
        }

        public Objeto Get(Guid guid)
        { 
            using (CoreEntities db = this.entities)
            {
                return db.Objetos.ToList().Where(x => x.Guid == guid).FirstOrDefault();
            }
        }

        public IEnumerable<Objeto> Get()
        {
            using (CoreEntities db = this.entities)
            {
                return db.Objetos.SoftList().ToList();
            }
        }

        public Objeto Update(Objeto item)
        {
            using (var db = this.entities)
            {
                //item.EntityState += System.Data.EntityState.Modified;
                db.Objetos.Attach(item);
                db.Entry(item).State = EntityState.Modified; 
                db.SaveChanges();
                return Get(item.Guid);
            }
        }

        public void Delete(Guid guid)
        {
            using (var db = this.entities)
            {
                Objeto item = db.Objetos.Find(guid);
                db.Objetos.Remove(item);
                db.SaveChanges();
            }
        }
    }
}
